package com.cjj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjj.common.convention.exception.ClientException;
import com.cjj.common.convention.exception.ServiceException;
import com.cjj.dao.entity.RunnerOrder;
import com.cjj.dao.mapper.RunnerOrderMapper;
import com.cjj.dto.req.AcceptRunnerOrderReqDTO;
import com.cjj.dto.req.CreateRunnerOrderReqDTO;
import com.cjj.dto.req.UpdateByRunnerOrderIdReqDTO;
import com.cjj.service.RunnerOrderService;
import com.cjj.service.ServiceOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.cjj.common.convention.errorcode.BaseErrorCode.SERVICE_ERROR;

/**
 * <p>
 * 跑腿订单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2025-10-25
 */
@Service
@RequiredArgsConstructor
public class RunnerOrderServiceImpl extends ServiceImpl<RunnerOrderMapper, RunnerOrder> implements RunnerOrderService {

    private final ServiceOrderService serviceOrderService;

    /**
     * 创建跑腿订单
     */
    @Override
    public void createOrder(CreateRunnerOrderReqDTO createRunnerOrderReqDTO) {
        baseMapper.insert(BeanUtil.copyProperties(createRunnerOrderReqDTO, RunnerOrder.class));
    }

    /**
     *骑手查看可用的跑腿订单
     * @param pageNum 页数
     * @param pageSize 页数大小
     * @return
     */
    @Override
    public IPage<RunnerOrder> getAvailableOrders(Integer pageNum, Integer pageSize) {
        // 校验分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
        pageSize = Math.min(pageSize, 100); // 限制最大页大小

        //查到serviceOrder数据库，订单状态为reviewed的跑腿订单
        List<Long> orderIdList = serviceOrderService.selectReviewedRunnerOrder();

        // 如果订单列表为空，直接返回空分页
        if (orderIdList == null || orderIdList.isEmpty()) {
            return new Page<>(pageNum, pageSize);
        }

        // 创建分页对象
        Page<RunnerOrder> page = new Page<>(pageNum, pageSize);

        // 构建查询条件：runnerOrderId在orderIdList中
        LambdaQueryWrapper<RunnerOrder> wrapper = Wrappers.lambdaQuery(RunnerOrder.class)
                .in(RunnerOrder::getOrderId, orderIdList)
                .orderByDesc(RunnerOrder::getCreateTime);

        return baseMapper.selectPage(page, wrapper);
    }

    /**
     * 通过runnerOrderId实现更新跑腿订单金额
     * @param updateByRunnerOrderIdReqDTO
     */
    @Override
    public void updateByOrderId(UpdateByRunnerOrderIdReqDTO updateByRunnerOrderIdReqDTO) {
        LambdaQueryWrapper<RunnerOrder> lambdaQuery = Wrappers.lambdaQuery(RunnerOrder.class);
        lambdaQuery.eq(RunnerOrder::getRunnerOrderId, updateByRunnerOrderIdReqDTO.getRunnerOrderId());
        RunnerOrder runnerOrder = baseMapper.selectOne(lambdaQuery);
        runnerOrder.setReward(updateByRunnerOrderIdReqDTO.getReward());
        int count = baseMapper.updateById(runnerOrder);
        if (count != 1){
            throw new ServiceException(SERVICE_ERROR);
        }
    }

    /**
     *骑手接单
     */
    @Transactional
    @Override
    public void acceptRunnerOrder(AcceptRunnerOrderReqDTO acceptRunnerOrderReqDTO) {

        if (acceptRunnerOrderReqDTO == null){
            throw new ServiceException(SERVICE_ERROR);
        }

        //查询要修改的订单信息
        LambdaQueryWrapper<RunnerOrder> eq = Wrappers.lambdaQuery(RunnerOrder.class)
                .eq(RunnerOrder::getOrderId, acceptRunnerOrderReqDTO.getOrderId());
        RunnerOrder runnerOrder = baseMapper.selectOne(eq);

        //检查订单是否超时
        if (runnerOrder.getDeadline().isBefore(LocalDateTime.now())) {
            throw new ClientException("订单已超时，无法接单");
        }

        //修改订单总表中订单的状态为已接单
        serviceOrderService.acceptOrder(acceptRunnerOrderReqDTO.getOrderId());

        //修改跑腿订单，将骑手id放到表中
        runnerOrder.setRunnerId(acceptRunnerOrderReqDTO.getUserId());
        baseMapper.updateById(runnerOrder);
    }

    /**
     * 骑手完成订单，修改订单表的订单的状态为已完成
     * @param orderId 订单id
     */
    @Override
    public void completeRunnerOrder(Long orderId) {
        serviceOrderService.completedOrder(orderId);
    }


}
